const { Service } = require("egg");

class ChapterService extends Service {
    //添加章
    async addChapter(body) {
            try {
                const chapter = {
                    title: body.title,
                    book_id: body.book_id,
                    orderby: body.orderby,
                }
                await this.app.model.Chapter.create(chapter)
                return true
            } catch (error) {
                return false
            }
        }
        //获取章
    async getChapter(book_id) {
            try {
                const ChapterList = await this.app.model.Chapter.findAll({
                    order: [
                        ['orderby', "asc"]
                    ],
                    include: [{
                        model: this.app.model.Book,
                        as: "book"
                    }],
                    where: {
                        book_id
                    }
                })
                return ChapterList
            } catch (error) {
                return null
            }
        }
        //删除章
    async deleteChapter(id) {
            try {
                await this.app.model.Section.destroy({
                    where:{
                        chapter_id:id
                    }
                })
                await this.app.model.Chapter.destroy({
                    where: {
                        id
                    }
                })
                return true
            } catch (error) {
                return false
            }
        }
        //更新章
    async updateChapter(id, body) {
        try {
            const chapter = {
                title: body.title,
                book_id: body.book_id,
                orderby: body.orderby,
            }
            await this.app.model.Chapter.update(chapter, {
                where: {
                    id
                }
            })
            return true
        } catch (error) {
            return false
        }
    }

}

module.exports = ChapterService